package com.waikuai.shop.controller;

import com.waikuai.shop.common.result.Result;
import com.waikuai.shop.entity.ProductCategory;
import com.waikuai.shop.service.ProductCategoryService;
import com.waikuai.shop.vo.CategoryTreeVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/categories")
@RequiredArgsConstructor
@Validated
public class ProductCategoryController {

    private final ProductCategoryService productCategoryService;

    @GetMapping
    public Result<List<ProductCategory>> getAllCategories() {
        try {
            List<ProductCategory> categories = productCategoryService.getEnabledCategories();
            log.info("获取所有分类列表成功，数量: {}", categories.size());
            return Result.success("获取分类列表成功", categories);
        } catch (Exception e) {
            log.error("获取所有分类列表失败: {}", e.getMessage(), e);
            return Result.error("获取分类列表失败");
        }
    }

    @GetMapping("/tree")
    public Result<List<CategoryTreeVO>> getCategoryTree() {
        try {
            List<CategoryTreeVO> categoryTree = productCategoryService.getCategoryTree();
            log.info("获取分类树结构成功，数量: {}", categoryTree.size());
            return Result.success("获取分类树成功", categoryTree);
        } catch (Exception e) {
            log.error("获取分类树结构失败: {}", e.getMessage(), e);
            return Result.error("获取分类树失败");
        }
    }

    @GetMapping("/top-level")
    public Result<List<ProductCategory>> getTopLevelCategories() {
        try {
            List<ProductCategory> categories = productCategoryService.getTopLevelCategories();
            log.info("获取顶级分类列表成功，数量: {}", categories.size());
            return Result.success("获取顶级分类成功", categories);
        } catch (Exception e) {
            log.error("获取顶级分类列表失败: {}", e.getMessage(), e);
            return Result.error("获取顶级分类失败");
        }
    }

    @GetMapping("/parent/{parentId}")
    public Result<List<ProductCategory>> getCategoriesByParentId(@PathVariable Long parentId) {
        try {
            List<ProductCategory> categories = productCategoryService.getCategoriesByParentId(parentId);
            log.info("根据父分类ID获取子分类列表成功，父分类ID: {}, 数量: {}", parentId, categories.size());
            return Result.success("获取子分类成功", categories);
        } catch (Exception e) {
            log.error("根据父分类ID获取子分类列表失败，父分类ID: {}, 错误: {}", parentId, e.getMessage(), e);
            return Result.error("获取子分类失败");
        }
    }

    @GetMapping("/enabled")
    public Result<List<ProductCategory>> getEnabledCategories() {
        try {
            List<ProductCategory> categories = productCategoryService.getEnabledCategories();
            log.info("获取启用的分类列表成功，数量: {}", categories.size());
            return Result.success("获取启用分类成功", categories);
        } catch (Exception e) {
            log.error("获取启用的分类列表失败: {}", e.getMessage(), e);
            return Result.error("获取启用分类失败");
        }
    }

    @PostMapping
    public Result<String> createCategory(@Valid @RequestBody ProductCategory category) {
        try {
            if (productCategoryService.checkCategoryNameExists(category.getCategoryName(), null)) {
                return Result.error("分类名称已存在");
            }

            boolean result = productCategoryService.createCategory(category);
            if (result) {
                log.info("创建商品分类成功，分类名称: {}", category.getCategoryName());
                return Result.success("创建分类成功");
            } else {
                return Result.error("创建分类失败");
            }
        } catch (Exception e) {
            log.error("创建商品分类失败，分类名称: {}, 错误: {}", category.getCategoryName(), e.getMessage(), e);
            return Result.error("创建分类失败");
        }
    }

    @PutMapping("/{categoryId}")
    public Result<String> updateCategory(
            @PathVariable Long categoryId,
            @Valid @RequestBody ProductCategory category) {
        try {
            if (productCategoryService.checkCategoryNameExists(category.getCategoryName(), categoryId)) {
                return Result.error("分类名称已存在");
            }

            category.setId(categoryId);
            boolean result = productCategoryService.updateCategory(category);
            if (result) {
                log.info("更新商品分类成功，分类ID: {}", categoryId);
                return Result.success("更新分类成功");
            } else {
                return Result.error("更新分类失败");
            }
        } catch (Exception e) {
            log.error("更新商品分类失败，分类ID: {}, 错误: {}", categoryId, e.getMessage(), e);
            return Result.error("更新分类失败");
        }
    }

    @DeleteMapping("/{categoryId}")
    public Result<String> deleteCategory(@PathVariable Long categoryId) {
        try {
            Integer productCount = productCategoryService.countProductsByCategoryId(categoryId);
            if (productCount > 0) {
                return Result.error("该分类下还有商品，无法删除");
            }

            List<ProductCategory> children = productCategoryService.getCategoriesByParentId(categoryId);
            if (!children.isEmpty()) {
                return Result.error("该分类下还有子分类，无法删除");
            }

            boolean result = productCategoryService.deleteCategory(categoryId);
            if (result) {
                log.info("删除商品分类成功，分类ID: {}", categoryId);
                return Result.success("删除分类成功");
            } else {
                return Result.error("删除分类失败");
            }
        } catch (Exception e) {
            log.error("删除商品分类失败，分类ID: {}, 错误: {}", categoryId, e.getMessage(), e);
            return Result.error("删除分类失败");
        }
    }

    @GetMapping("/{categoryId}")
    public Result<ProductCategory> getCategoryDetail(@PathVariable Long categoryId) {
        try {
            ProductCategory category = productCategoryService.getById(categoryId);
            if (category == null) {
                return Result.error("分类不存在");
            }

            Integer productCount = productCategoryService.countProductsByCategoryId(categoryId);
            log.info("获取分类详情成功，分类ID: {}", categoryId);
            return Result.success("获取分类详情成功", category);
        } catch (Exception e) {
            log.error("获取分类详情失败，分类ID: {}, 错误: {}", categoryId, e.getMessage(), e);
            return Result.error("获取分类详情失败");
        }
    }

    @GetMapping("/{categoryId}/product-count")
    public Result<Integer> getProductCount(@PathVariable Long categoryId) {
        try {
            Integer count = productCategoryService.countProductsByCategoryId(categoryId);
            log.info("统计分类商品数量成功，分类ID: {}, 数量: {}", categoryId, count);
            return Result.success("统计商品数量成功", count);
        } catch (Exception e) {
            log.error("统计分类商品数量失败，分类ID: {}, 错误: {}", categoryId, e.getMessage(), e);
            return Result.error("统计商品数量失败");
        }
    }

    @GetMapping("/check-name")
    public Result<Boolean> checkCategoryName(
            @RequestParam @NotBlank String categoryName,
            @RequestParam(required = false) Long excludeId) {
        try {
            boolean exists = productCategoryService.checkCategoryNameExists(categoryName, excludeId);
            return Result.success("检查完成", exists);
        } catch (Exception e) {
            log.error("检查分类名称失败: {}", e.getMessage(), e);
            return Result.error("检查分类名称失败");
        }
    }

    @GetMapping("/{categoryId}/path")
    public Result<List<ProductCategory>> getCategoryPath(@PathVariable Long categoryId) {
        try {
            List<ProductCategory> path = productCategoryService.getEnabledCategories();
            log.info("获取分类路径成功，分类ID: {}", categoryId);
            return Result.success("获取分类路径成功", path);
        } catch (Exception e) {
            log.error("获取分类路径失败，分类ID: {}, 错误: {}", categoryId, e.getMessage(), e);
            return Result.error("获取分类路径失败");
        }
    }
}
